<template>
  <div class="content">
    <div class="zhan"></div>
    <div class="top" @click="updateAddress">
      <div class="top-left">
        <div class="info">
          <i-icon
            class="coordinates"
            type="coordinates"
            size="28"
            color="#dddddd"
          />
          <div>
            收货人：
            <p>{{setAdderss.addressContact}}</p>
            <span>{{setAdderss.addressPhone}}</span>
          </div>
        </div>
        <div
          class="add"
        >{{setAdderss.province}}{{setAdderss.city}}{{setAdderss.area}}{{setAdderss.addressInfo}}</div>
      </div>
      <i-icon type="enter" size="28" color="#a2a2a2" />
    </div>
    <div class="operation">
      <div v-for="(item,index) in list" :key="index">
        <span>{{item.label}}</span>
        <input
          v-model="stockForm[item.key]"
          type="number"
          :placeholder="item.placeholder"
          :disabled="item.disabled"
          @input="stockFormChange(item)"
        />
      </div>
    </div>
    <div class="operation">
      <div v-for="(item,index) in list2" :key="index">
        <span>{{item.label}}</span>
        <input
          v-if="item.key === 'pension'"
          v-model="stockForm[item.key]"
          type="digit"
          :placeholder="item.placeholder"
          :disabled="item.disabled"
        />
        <picker
          v-else
          class="proportionClass"
          @change="proportionChange"
          :range="swiperList"
          range-key="goodsTypeName"
          :value="pickerIndex"
        >
          <span v-if="!pickerShow">请选择</span>
          <span v-else>{{pickerShow}}</span>
          <i-icon type="enter" size="16" color="#696969" />
        </picker>
      </div>
    </div>
    <p class="hint">进货需要冻结您的部分余额，请确保余额账户资金充足</p>
    <button class="btn" @click="stockClick">确定</button>
  </div>
</template>

<script>
import {
  SET_ON_CILCK_STOCK,
  GET_STOCK_SHIPPING_FEE,
  FIND_SHOP_PLATFORM_TYPE_LIST_API,
  YST_FIND_ACCOUNT_BALANCE,
  CREATE_PROVIDER_ORDER,
  FIND_GOODS_TYPE_LIST_API
} from '@/api'
import { getCurrentPageParams } from '@/utils'

export default {
  components: {},
  props: {},
  data () {
    return {
      form: {},
      stockForm: {
        stockSupplyCost: '', // 供货价
        goodsNum: '', // 数据供货数量
        stockSupplyCostAll: '', // 商品总金额
        lockAmount: '', // 赊货锁额
        shippingFee: '', // 运费
        pension: '', // 售卖价格
        goodsTypeId: '' // 选择分类
      },
      swiperList: [],
      pickerIndex: '',
      pickerShow: '',
      allAmount: '',
      setAdderss: {}
    }
  },
  computed: {
    account () {
      return this.$store.state.account
      // return this.$cookie.get('account')
    },
    adminInfo () {
      return this.$cookie.get('new-admin-info')
    },
    list () {
      return [
        {
          label: '供货价',
          disabled: true,
          placeholder: '供货价',
          type: 'text',
          key: 'stockSupplyCost'
        },
        {
          // label: `进货数量(最大${this.form.stockSupplyNum}件)`, // to do 同步安卓
          label: `进货数量(最大${this.form.maxStockNum}件)`,
          disabled: false,
          placeholder: '请输入',
          type: 'number',
          key: 'goodsNum'
        },
        {
          label: '商品总金额',
          disabled: true,
          placeholder: '输入进货数量后计算',
          type: 'text',
          key: 'stockSupplyCostAll'
        },
        {
          label: `赊货锁额(${this.form.stockCreditPre}%)`,
          disabled: true,
          placeholder: '输入进货数量后计算',
          type: 'text',
          key: 'lockAmount'
        },
        {
          label: '运费',
          disabled: true,
          placeholder: '运费',
          type: 'text',
          key: 'shippingFee'
        }
      ]
    },
    list2 () {
      return [
        {
          label: '零售价(您的售卖价格)',
          disabled: false,
          placeholder: '请输入',
          type: 'digit',
          key: 'pension'
        },
        {
          label: '选择分类',
          disabled: true,
          placeholder: '请选择',
          type: 'text',
          key: 'goodsTypeId'
        }
      ]
    }
  },
  watch: {},
  created () {},
  mounted () {},
  onUnload () {
    this.$cookie.remove('setAdderss')
  },
  onShow () {
    this.stockForm = {
      stockSupplyCost: '', // 供货价
      goodsNum: '', // 数据供货数量
      stockSupplyCostAll: '', // 商品总金额
      lockAmount: '', // 赊货锁额
      shippingFee: '', // 运费
      pension: '', // 售卖价格
      goodsTypeId: '' // 选择分类
    }
    this.pickerIndex = ''
    this.pickerShow = ''
    this.init()
    // this.getDisShopList()
    this.findGoodsTypeListApi()
    this.getBalance()
  },
  methods: {
    updateAddress () {
      this.$cookie.set('setAdderss', this.setAdderss)
      // to do 没有高保，暂时先注释了
      this.$router.push(`/pages/data-analyze/stock/set-adderss/main`)
    },
    stockFormChange (item) {
      const vm = this
      if (item.key === 'goodsNum') {
        vm.stockForm.stockSupplyCostAll = (
          vm.stockForm.goodsNum *
          vm.stockForm.stockSupplyCost *
          1
        ).toFixed(2)
        vm.stockForm.lockAmount = (
          vm.stockForm.goodsNum *
          vm.stockForm.stockSupplyCost *
          vm.form.stockCreditPre *
          0.01
        ).toFixed(2)
        // vm.stockForm.lockAmount = vm.from.stockCreditPre
        //   ? (
        //     vm.stockForm.goodsNum *
        //       vm.stockForm.stockSupplyCost *
        //       vm.form.stockCreditPre *
        //       0.01
        //   ).toFixed(2)
        //   : 0
        if (vm.stockForm.goodsNum) {
          vm.getStockShippingFee()
        } else {
          vm.stockForm.shippingFee = 0
        }
      }
    },
    proportionChange (e) {
      const vm = this
      vm.pickerIndex = e.target.value
      vm.pickerShow = vm.swiperList[e.target.value].goodsTypeName
      vm.stockForm.goodsTypeId = vm.swiperList[e.target.value].goodsTypeId
    },
    stockClick () {
      const vm = this
      // 1.查余额够不够支付
      // 2.先onClickStock锁额
      // 3.直接/store-api/store/stock/createProviderOrder创建订单就完了
      let count = 0
      let adderssAll = 0
      let adderssCount = 0
      for (let key in vm.stockForm) {
        if (vm.stockForm[key] !== '') {
          count++
        }
      }
      if (count < 7) {
        vm.$toast('请确保信息的完整性')
        return false
      }
      for (let key in vm.setAdderss) {
        if (key) {
          adderssAll++
        }
        if (vm.setAdderss[key]) {
          adderssCount++
        }
      }
      if (adderssCount < adderssAll) {
        vm.$toast('请确保地址完整')
        return false
      }

      if (vm.form.maxStockNum < Number(vm.stockForm.goodsNum)) {
        vm.$toast('输入进货数不能大于最大件数')
        return false
      }

      vm
        .$dialog(
          `此订单锁定余额￥${vm.stockForm.lockAmount}`,
          '温馨提示',
          '#ef250b'
        )
        .then(() => {
          if (vm.allAmount < vm.stockForm.stockSupplyCostAll) {
            vm
              .$dialog('您的余额不足，是否前往充值', '温馨提示', '#ef250b')
              .then(() => {
                vm.$router.push('/pages/mine/balance/main')
              })
              .catch(() => {})
            return false
          } else if (!vm.stockForm.lockAmount) {
            vm.$toast('赊货锁额不能为0')
          }

          let params = {
            stockShopId: vm.account.shopId,
            shopId: vm.form.shopId,
            lockAmount:
              vm.stockForm.goodsNum *
              vm.stockForm.stockSupplyCost *
              (vm.form.stockCreditPre * 0.01),
            goodsNo: vm.form.goodsNo
          }

          SET_ON_CILCK_STOCK(params)
            .then(r => {
              if (r.data.code === '0') {
                vm.cerateProviderOrder()
              } else if (r.data.code === '-1') {
                vm
                  .$dialog('您的余额不足，是否前往充值', '温馨提示', '#ef250b')
                  .then(() => {
                    vm.$router.push('/pages/mine/balance/main')
                  })
                  .catch(() => {})
              } else {
                vm.$toast(r.data.message)
              }
            })
            .catch(e => {
              console.error(e)
            })
        })
        .catch(() => {})
    }, // 分销一键进货
    getStockShippingFee () {
      const vm = this
      let params = [
        {
          goodsNo: vm.form.goodsNo,
          goodsNum: vm.stockForm.goodsNum
        }
      ]
      GET_STOCK_SHIPPING_FEE(params)
        .then(r => {
          if (r.data.code === '0') {
            vm.stockForm.shippingFee = r.data.data
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    getDisShopList () {
      const vm = this
      let params = {
        providerId: vm.account.providerId,
        isShow: '1',
        parentId: 0
      }
      FIND_SHOP_PLATFORM_TYPE_LIST_API(params)
        .then(r => {
          if (r.data.code === '0') {
            vm.swiperList = r.data.data
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 平台的，不用了
    findGoodsTypeListApi () {
      const vm = this
      FIND_GOODS_TYPE_LIST_API(vm.account.shopId, 0)
        .then(r => {
          if (r.data.code === '0') {
            vm.swiperList = r.data.data
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    },
    getBalance () {
      const vm = this
      let params = {
        identity: 'SHOP',
        relateId: vm.account.shopId
      }

      YST_FIND_ACCOUNT_BALANCE(params)
        .then(r => {
          if (r.data.code === '0') {
            let { allAmount } = r.data.data
            vm.allAmount = allAmount
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    cerateProviderOrder () {
      const vm = this
      let list = [
        {
          goodsNo: vm.form.goodsNo,
          goodsNum: vm.stockForm.goodsNum,
          // goodsSpecId: vm.stockForm.goodsSpecList[0].goodsSpecId, // to do 没有填这个参数的地方
          goodsTypeId: vm.stockForm.goodsTypeId,
          pension: vm.stockForm.pension,
          retailAmount: Number(vm.stockForm.pension),
          stockCreditPre: vm.form.stockCreditPre,
          goodsSpecId: 0
        }
      ]
      let params = {
        customerId: vm.account.shopId,
        shopId: vm.form.shopId,
        // shopId: vm.account.shopId,
        orderType: 'stock',
        addressContact: vm.setAdderss.addressContact, // 收货人
        addressPhone: vm.setAdderss.addressPhone, // 收货人手机号码
        province: vm.setAdderss.province, // 省
        city: vm.setAdderss.city, // 市
        area: vm.setAdderss.area, // 区
        addressInfo: vm.setAdderss.addressInfo, // 地址
        shippingFee: vm.stockForm.shippingFee, // 运费
        orderGoodsList: list,
        shippingMode: '0',
        lockAmount: vm.stockForm.lockAmount
      }
      CREATE_PROVIDER_ORDER(params)
        .then(r => {
          if (r.data.code === '0') {
            let label = '进货成功'
            let btnText = '查看订单'
            vm.$router.replace(
              `/pages/data-analyze/stock/succeed/main?label=${label}&btnText=${btnText}&type=stock`
            )
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    init () {
      const vm = this
      let item = JSON.parse(getCurrentPageParams('item'))
      vm.form = item
      vm.stockForm.stockSupplyCost = vm.form.stockSupplyCost
      // for (let key in vm.stockForm) {
      //   vm.stockForm[key] = vm.form[key]
      // }
      if (vm.$cookie.get('setAdderss')) {
        vm.setAdderss = { ...vm.$cookie.get('setAdderss') }
      } else {
        vm.setAdderss = {
          // province: vm.account.province,
          // area: vm.account.area,
          // city: vm.account.city,
          // addressInfo: vm.account.shopAddress,
          // addressContact: vm.account.shopName,
          // addressPhone: vm.adminInfo.phone
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'static/styles/color.scss';
.content {
  background: #f6f8f9;
  > .zhan {
    height: 20px;
  }
  > .top {
    width: 95%;
    margin: auto;
    background: #fff;
    border-radius: 6px;
    display: flex;
    align-items: center;
    font-size: 14px;
    margin-bottom: 20px;
    > .top-left {
      width: 90%;
      > .info {
        display: flex;
        align-items: center;
        height: 40px;
        > .coordinates {
          width: 30px;
        }
        > div {
          display: flex;
          align-items: center;
          color: #000;
          span {
            color: #ef250b;
            margin-left: 5px;
          }
        }
      }
      > .add {
        width: calc(90% - 30px);
        margin-left: 30px;
        color: #696969;
        padding-bottom: 15px;
      }
    }
  }
  > .operation {
    width: 95%;
    margin: 0 auto 20px;
    color: #000;
    background: #fff;
    border-radius: 6px;
    div {
      width: 95%;
      margin: auto;
      height: 40px;
      font-size: 14px;
      border-bottom: 1px solid #fafbfc;
      display: flex;
      align-items: center;
      justify-content: space-between;
      input {
        color: #686868;
        text-align: right;
      }
      .proportionClass {
        span {
          color: #696969;
        }
      }
    }
  }
  > .hint {
    font-size: 13px;
    color: #ef250b;
    width: 95%;
    margin: 0 auto 25px;
  }
  > .btn {
    width: 95%;
    margin: auto;
    height: 45px;
    font-size: 14px;
    color: #fff;
    line-height: 45px;
    border-radius: 25px;
    background: linear-gradient(to right, $new-red-tint, $new-red-dark);
  }
}
</style>
